import router from './router'
import { useUserStore } from '@/store/user'
import { usePermissionStore } from '@/store/permission'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken, removeToken } from '@/utils/auth'
import { RouteLocationNormalized, NavigationGuardNext, RouteRecordRaw } from 'vue-router'
import { ElMessage } from 'element-plus'
import { AppRouteRecordRaw } from '@/types/router'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/auth-redirect']

router.beforeEach(async(to: RouteLocationNormalized, _: RouteLocationNormalized, next: NavigationGuardNext) => {
  NProgress.start()
  console.log('Route guard - Current path:', to.path)

  const userStore = useUserStore()
  const permissionStore = usePermissionStore()

  // 确定用户是否已登录
  const hasToken = getToken()
  console.log('Route guard - Has token:', !!hasToken)

  if (hasToken) {
    if (to.path === '/login') {
      // 已登录则重定向到首页
      next({ path: '/' })
      NProgress.done()
    } else {
      try {
        // 确定用户是否已获取权限角色
        const hasRoles = userStore.roles && userStore.roles.length > 0
        const hasRoutes = permissionStore.routes.length > 0
        console.log('Route guard - Has roles:', hasRoles)
        console.log('Route guard - Has routes:', hasRoutes)

        if (!hasRoles) {
          console.log('Route guard - Getting user info...')
          // 获取用户信息
          const userInfo = await userStore.getInfo()
          console.log('Route guard - User roles:', userInfo.roles)
          
          if (!userInfo.roles || userInfo.roles.length === 0) {
            throw new Error('获取用户角色失败')
          }

          console.log('Route guard - Generating routes...')
          // 根据角色生成可访问路由映射
          const accessRoutes = await permissionStore.generateRoutes(userInfo)
          console.log('Route guard - Generated routes:', JSON.stringify(accessRoutes))
          
          if (!accessRoutes || accessRoutes.length === 0) {
            throw new Error('生成路由失败')
          }

          // 动态添加可访问路由
          accessRoutes.forEach(route => {
            console.log('Route guard - Adding route:', route.name)
            if (!router.hasRoute(route.name as string)) {
              router.addRoute(route as unknown as RouteRecordRaw)
            }
          })

          // 确保 addRoutes 完成
          next({ ...to, replace: true })
        } else if (!hasRoutes) {
          console.log('Route guard - Regenerating routes...')
          // 如果有角色但没有路由，重新生成路由
          const userInfo = {
            id: userStore.userInfo?.id || 0,
            roles: userStore.roles
          }
          const accessRoutes = await permissionStore.generateRoutes(userInfo)
          console.log('Route guard - Regenerated routes:', JSON.stringify(accessRoutes))
          
          if (!accessRoutes || accessRoutes.length === 0) {
            throw new Error('生成路由失败')
          }

          // 动态添加可访问路由
          accessRoutes.forEach(route => {
            console.log('Route guard - Adding route:', route.name)
            if (!router.hasRoute(route.name as string)) {
              router.addRoute(route as unknown as RouteRecordRaw)
            }
          })

          // 确保 addRoutes 完成
          next({ ...to, replace: true })
        } else {
          next()
        }
      } catch (error) {
        console.error('Route guard - Error:', error)
        // 移除 token 并重定向到登录页
        userStore.$reset()
        permissionStore.resetRoutes()
        removeToken()
        ElMessage.error(error instanceof Error ? error.message : '认证失败，请重新登录')
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  } else {
    // 没有 token
    if (whiteList.indexOf(to.path) !== -1) {
      // 免登录白名单，直接进入
      next()
    } else {
      // 重定向到登录页
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
